package com.ruoyi.factory.epros.service.impl;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.bom.domain.BomPrice;
import com.ruoyi.factory.common.domain.AjaxBean;
import com.ruoyi.factory.epros.common.SendUtils;
import com.ruoyi.factory.epros.domain.DeptInfo;
import com.ruoyi.factory.epros.domain.PerByPost;
import com.ruoyi.factory.epros.domain.PersonInfo;
import com.ruoyi.factory.epros.domain.PostInfo;
import com.ruoyi.factory.epros.service.IEpDataSyncService;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import com.ruoyi.factory.qylock.utils.SignHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * @ClassName EpDataSyncService
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2023/2/9 17:22
 **/
@EnableScheduling
@Service
public class EpDataSyncServiceImpl implements IEpDataSyncService {

    protected final Logger logger = LoggerFactory.getLogger(EpDataSyncServiceImpl.class);

    @Value("${epros.sendUrl}")
    private String sendEprosUrl;
    @Value("${erp.oracle.url}")
    private String oracleUrl;
    @Value("${erp.oracle.username}")
    private String oracleUserName;
    @Value("${erp.oracle.password}")
    private String oraclePassword;

    /**
     * @author: Liujiaji
     * @date: 2023/2/10 10:50
     * @description: TODO 通过oracle获取人员信息并封装
     * @param: []
     * @return: void
     **/
    @Override
    public Object personByOr(String type){
        String sql="";

        // 定义oracle数据库的驱动的类
        String driverClass = "oracle.jdbc.OracleDriver";
        // 定义连接的oracle的url
        String url = oracleUrl;
        // 用户名
        String username = oracleUserName;
        // 密码
        String password = oraclePassword;

        // 定义Connection连接
        Connection conn = null;
        // 定义数据库的sql执行对象
        Statement stmt = null;

        // 定义查询结果的ResultSet对象
        ResultSet rs = null;

        PreparedStatement pst = null;

        ResultSet rst = null;

        List<PersonInfo> perlist = new ArrayList<>();
        List<DeptInfo> deplist = new ArrayList<>();
        List<PostInfo> postlist = new ArrayList<>();
        List<PerByPost> perPostlist = new ArrayList<>();
        try {
            // 注册数据库的驱动程序
            Class.forName(driverClass);
            // 获得数据库的连接
            DriverManager.setLoginTimeout(60);
            conn = DriverManager.getConnection(url, username, password);
            // 创建sql执行对象
            stmt = conn.createStatement();

            if(type.equals("1")){
                sql = "SELECT doc.code, doc.name, doc.mobile, doc.email, job.PK_PSNCL, dept.name deptname, dept.code deptcode, post.postcode, post.postname, job.endflag FROM BD_PSNDOC doc left join hi_psnjob job ON doc.pk_psndoc = job.pk_psndoc AND job.dr = 0 and job.lastflag = 'Y' left join org_dept dept on job.pk_dept = dept.pk_dept and dept.dr=0 left join om_post post on job.pk_post= post.pk_post and post.dr=0 where doc.dr=0";
            }else if(type.equals("2")){
                sql = "SELECT b.code, b.pk_fatherorg, b.name, b.pk_dept, s.code scode, s.name sname FROM org_dept b LEFT JOIN org_dept s on b.pk_fatherorg = s.pk_dept  where b.dr=0 and b.depttype=0 and  b.enablestate = 2";
            }else if(type.equals("3")){
                sql = "SELECT post.pk_dept, post.postname, post.postcode, dep.code FROM om_post post left join org_dept dep on post.pk_dept = dep.pk_dept and dep.dr=0 where post.enablestate = 2 and post.dr=0";
            }else if(type.equals("4")){
//                sql = "SELECT distinct doc.code, doc.name, doc.mobile, dept.name deptname, dept.code deptcode, post.postcode, post.postname FROM BD_PSNDOC doc left join BD_PSNJOB job on doc.pk_psndoc = job.pk_psndoc  and job.dr=0 and job.enddutydate is null and job.ISMAINJOB= 'Y' left join org_dept_v dept on job.pk_dept = dept.pk_dept and dept.dr=0  AND dept.ISLASTVERSION = 'Y' left join om_post post on job.pk_post= post.pk_post and post.dr=0 where doc.dr=0  and post.postname is not null";
                sql = "SELECT doc.code, doc.name, doc.mobile, dept.name deptname, dept.code deptcode, post.postcode, post.postname FROM BD_PSNDOC doc left join BD_PSNJOB job on doc.pk_psndoc = job.pk_psndoc and job.dr=0 and job.enddutydate is null left join org_dept dept on job.pk_dept = dept.pk_dept and dept.dr=0 left join om_post post on job.pk_post= post.pk_post and post.dr=0 where  doc.dr=0 and doc.enablestate = 2";
            }else if(type.equals("5")){
                sql = "SELECT doc.code, doc.name, doc.mobile, dept.name deptname, dept.code deptcode, post.postcode, post.postname FROM BD_PSNDOC doc left join BD_PSNJOB job on doc.pk_psndoc = job.pk_psndoc left join org_dept_v dept on job.pk_dept = dept.pk_dept left join om_post post on job.pk_post= post.pk_post";
            }

            pst = conn.prepareStatement(sql);
            rst = pst.executeQuery();
            int i = 0;
            //封装
            while (rst.next()) {
                if(type.equals("1")){
                    PersonInfo perinfo = new PersonInfo();
                    perinfo.setLoginName(rst.getString("CODE"));
                    perinfo.setTrueName(rst.getString("NAME"));
                    //如果是离职员工则删除
                    if("Y".equals(rst.getString("endflag"))){
                        perinfo.setStatus("2");
                    }else{
                        perinfo.setStatus("0");
                    }
                    if(null != rst.getString("mobile")){
                        perinfo.setPhoneStr(rst.getString("mobile"));
                    }
                    if(null != rst.getString("email")){
                        perinfo.setEmail(rst.getString("email"));
                    }
                    perinfo.setPostNum(rst.getString("POSTCODE"));
                    perinfo.setPostName(rst.getString("POSTNAME"));
                    perinfo.setOrgNum(rst.getString("DEPTCODE"));
                    perlist.add(perinfo);
                }else if(type.equals("2")){
                    DeptInfo deptInfo = new DeptInfo();
                    deptInfo.setOrgNum(rst.getString("CODE"));
                    deptInfo.setOrgName(rst.getString("NAME"));
                    if(StringUtils.isNotEmpty(rst.getString("SCODE"))){
                        deptInfo.setPerOrgNum(rst.getString("SCODE"));
                    }else{
                        deptInfo.setPerOrgNum("0");
                    }
                    deptInfo.setOrgStatus("0");
                    deplist.add(deptInfo);
                }else if(type.equals("3")){
                    PostInfo postInfo = new PostInfo();
                    postInfo.setDeptNum(rst.getString("CODE"));
                    postInfo.setPosName(rst.getString("POSTNAME"));
                    postInfo.setPostNum(rst.getString("POSTCODE"));
                    postInfo.setStatus("0");
                    postlist.add(postInfo);
                }else if(type.equals("4")){
                    PerByPost perByPost = new PerByPost();
                    perByPost.setLoginName(rst.getString("CODE"));
                    perByPost.setPostId(rst.getString("POSTCODE"));
                    perByPost.setStatus("0");
                    perPostlist.add(perByPost);
                }else if(type.equals("5")){
                    PerByPost perByPost = new PerByPost();
                    perByPost.setLoginName(rst.getString("CODE"));
                    perByPost.setPostId(rst.getString("POSTCODE"));
                    perByPost.setStatus("2");
                    perPostlist.add(perByPost);
                }

            }

            if(pst != null){
                pst.close();
            }
            if(rst != null){
                rst.close();
            }
            if (rs != null)
            {
                rs.close();
            }
            if (stmt != null)
            {
                stmt.close();
            }
            if (conn != null)
            {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(type.equals("1")){
            Map<String, List<PersonInfo>> pmap = new HashMap<>();
            pmap.put("data",perlist);
            return pmap;
        }else if(type.equals("2")){
            Map<String, List<DeptInfo>> pmap = new HashMap<>();
            pmap.put("data",deplist);
            return pmap;
        }else if(type.equals("3")){
            Map<String, List<PostInfo>> pmap = new HashMap<>();
            pmap.put("data",postlist);
            return pmap;
        }else if(type.equals("4")){
            Map<String, List<PerByPost>> pmap = new HashMap<>();
            pmap.put("data",perPostlist);
            return pmap;
        }else if(type.equals("5")){
            Map<String, List<PerByPost>> pmap = new HashMap<>();
            pmap.put("data",perPostlist);
            return pmap;
        }
        return null;
    }

    /**
     * @author: Liujiaji
     * @date: 2023/5/11 0011 11:05
     * @description: TODO 向epros发送同步信息
     * @param: [pram, type]
     * @return: void
     **/
    @Override
    public void toEpData(String pram, String type){
        if(type.equals("1")){
            String sendurl = sendEprosUrl+"/openService/saveUser";
            logger.info("请求epros同步人员信息, 入参: " + pram);
            String result = SendUtils.okHttpPost(sendurl, pram);
            logger.info("请求epros同步人员信息, 出参: " + result);
        }else if(type.equals("2")){
            String sendurl = sendEprosUrl+"/openService/saveOrg";
            logger.info("请求epros同步部门信息, 入参: " + pram);
            String result = SendUtils.okHttpPost(sendurl, pram);
            logger.info("请求epros同步部门信息, 出参: " + result);
        }else if(type.equals("3")){
            String sendurl = sendEprosUrl+"/openService/savePost";
            logger.info("请求epros同步岗位信息, 入参: " + pram);
            String result = SendUtils.okHttpPost(sendurl, pram);
            logger.info("请求epros同步岗位信息, 出参: " + result);
        }else if(type.equals("4")){
            String sendurl = sendEprosUrl+"/openService/saveUserPostRelated";
            logger.info("请求epros同步人员岗位关联信息, 入参: " + pram);
            String result = SendUtils.okHttpPost(sendurl, pram);
            logger.info("请求epros同步人员岗位关联信息, 出参: " + result);
        }
    }

    public String getDeptInfo () {
        //请求参数查询部门组织
        String url = "https://c2.yonyoucloud.com/iuap-api-gateway/yonbip/uspace/org/page_list";
        String token = SignHelper.getToken();
        url = url + "?access_token=" + token;
        Map<String, String> param = new HashMap<>();
        param.put("index", "1");
        param.put("size", "1000");
        String parm = net.sf.json.JSONObject.fromObject(param).toString();
        String res = OkHttpUtils.okHttpPost(url, parm);
        logger.info("请求友空间分页查询当前租户组织架构返参: " + res);
        String data = net.sf.json.JSONObject.fromObject(res).optString("data");
        //处理返回数据插入部门表
        String content = JSONObject.fromObject(data).optString("content");
        JSONArray jsonArray = JSONArray.fromObject(content);
        Map<String, String> map = new HashMap<>();
        for (Object o : jsonArray) {
            String id = JSONObject.fromObject(o).optString("id");
            String code = JSONObject.fromObject(o).optString("code").split("_")[0];
            //id和code匹配
            if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(code)) map.put(id, code);
        }
        List<DeptInfo> deplist = new ArrayList<>();
        for (Object o : jsonArray) {
            String name = JSONObject.fromObject(o).optString("name");
            String code = JSONObject.fromObject(o).optString("code").split("_")[0];
            String parentid = JSONObject.fromObject(o).optString("parentid");
            String enable = JSONObject.fromObject(o).optString("enable");

            DeptInfo deptInfo = new DeptInfo();
            deptInfo.setOrgNum(code);
            deptInfo.setOrgName(name);
            if (StringUtils.isNotEmpty(parentid)) {
                deptInfo.setPerOrgNum(map.get(parentid));
            } else {
                deptInfo.setPerOrgNum("0");
            }
            deptInfo.setOrgStatus("1".equals(enable) ? "0" : "2");
            deplist.add(deptInfo);
        }
        Map<String, List<DeptInfo>> pmap = new HashMap<>();
        pmap.put("data", deplist);
        String deps = JSONObject.fromObject(pmap).toString();
        return deps;
    }

    /**
     * 部门信息同步
     */
    public void deptupdate(){
        String param = "{\n" +
                "    \"data\":[\n" +
                "        {\n" +
                "            \"orgNum\":\"1002\",\n" +
                "            \"orgName\":\"沧州润孚\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"orgNum\":\"2001\",\n" +
                "            \"orgName\":\"锦州豪润达\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"orgNum\":\"2002\",\n" +
                "            \"orgName\":\"上海萱润\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        }\n" +
                "        ,\n" +
                "        {\n" +
                "            \"orgNum\":\"2003\",\n" +
                "            \"orgName\":\"新加坡瑞丰\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        }\n" +
                "        ,\n" +
                "        {\n" +
                "            \"orgNum\":\"3001\",\n" +
                "            \"orgName\":\"河南润孚\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        }\n" +
                "        ,\n" +
                "        {\n" +
                "            \"orgNum\":\"5001\",\n" +
                "            \"orgName\":\"瑞丰宏泰\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"1\"\n" +
                "        }\n" +
                "        ,\n" +
                "        {\n" +
                "            \"orgNum\":\"666\",\n" +
                "            \"orgName\":\"虚拟货代组织\",\n" +
                "            \"perOrgNum\":\"1001\",\n" +
                "            \"orgStatus\":\"2\"\n" +
                "        }\n" +
                "       \n" +
                "    ]\n" +
                "}";
        toEpData(String.valueOf(2),param);

    }

    public static void main(String[] args) {
        String s = "100101_1001".split("_")[0];
        String s2 = "100102".split("_")[0];
        System.out.println("输出s"+s);
        System.out.println("输出s2"+s2);
    }
}
